<?php

namespace app\admin\controller\test;

use app\common\controller\Backend;
use app\admin\model\test\Itembank;
use app\admin\model\test\Testitem as TestitemModel;
use app\admin\model\test\Testuser;

/**
 * 试卷试题管理
 *
 * @icon fa fa-circle-o
 */
class Testitem extends Backend
{
    
    /**
     * Testitem模型对象
     * @var \app\admin\model\test\Testitem
     */
    protected $model = null;

    protected $test = null;

    public function _initialize()
    {
        parent::_initialize();

        $test_id = $this->request->param('test_id');
        $this->test = \app\admin\model\test\Test::get($test_id);
        if (!$this->test) {
            $this->error('未找到对应试卷');
        }
        $this->assignconfig('test_id', $test_id);
        
        $this->model = new \app\admin\model\test\Testitem;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
		$this->view->assign('test', $this->test);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
			$condition = ['test_id' => $this->test['id']];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
					->where($condition)
                    ->with(['test','itembank'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
					
            $list = $this->model
					->where($condition)
                    ->with(['test','itembank'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','weigh','number','score']);
                $row->visible(['test']);
				$row->getRelation('test')->visible(['title']);
				$row->visible(['itembank']);
				$row->getRelation('itembank')->visible(['title','type']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

	public function randomtest(){
		
		//获取参数
		$this->checkTest();
		$judge_number = empty($this->request->request('judge_number')) ? 0 : intval($this->request->request('judge_number'));
		$judge_score = $this->request->request('judge_score');
		$onechoice_number = $this->request->request('onechoice_number');
		$onechoice_score = $this->request->request('onechoice_score');
		$manychoice_number = $this->request->request('manychoice_number');
		$manychoice_score = $this->request->request('manychoice_score');
		
		//验证
		if(!$judge_number && !$onechoice_number && !$manychoice_number){
			$this->error('请最少填写一种类型题');	
		}
		if($judge_number && !$judge_score){
			$this->error('判断题分数未设置');
		}
		if($onechoice_number && !$onechoice_score){
			$this->error('单选题分数未设置');
		}
		if($manychoice_number && !$manychoice_score){
			$this->error('多选题分数未设置');
		}
		//清空所有
		TestitemModel::where(['test_id'=>$this->test['id']])->delete();
		$number = 1;
		//根据科目下所有类型题
		if($judge_number > 0){
			$judgeItemList = Itembank::where(['type'=>'judge'])->column('id');
			if($judge_number < count($judgeItemList)){
				$judgeItemList = array_rand($judgeItemList,$judge_number);
			}
			foreach($judgeItemList as $key=>$val){
				$testitem           = new $this->model;
				$testitem->test_id  = $this->test['id'];
				$testitem->item_id  = $val;
				$testitem->score    = $judge_score;
				$testitem->save();
				$number++;
			}
		}
		if($onechoice_number > 0){
			$onechoiceItemList = Itembank::where(['type'=>'onechoice'])->column('id');
			if($onechoice_number < count($onechoiceItemList)){
				$onechoiceItemList = array_rand($onechoiceItemList,$onechoice_number);
			}
			foreach($onechoiceItemList as $key=>$val){
				$testitem           = new $this->model;
				$testitem->test_id  = $this->test['id'];
				$testitem->item_id  = $val;
				$testitem->score    = $onechoice_score;
				$testitem->save();
				$number++;
			}
		}
		if($manychoice_number> 0){
			$manychoiceItemList = Itembank::where(['type'=>'manychoice'])->column('id');
			if($manychoice_number < count($manychoiceItemList)){
				$manychoiceItemList = array_rand($manychoiceItemList,$manychoice_number);
			}
			foreach($manychoiceItemList as $key=>$val){
				$testitem           = new $this->model;
				$testitem->test_id  = $this->test['id'];
				$testitem->item_id  = $val;
				$testitem->score    = $manychoice_score;
				$testitem->save();
				$number++;
			}
		}
		//统计试卷总分
		$total_score = $this->model->where('test_id', $this->test['id'])->sum('score');
		$this->test->total_score = $total_score;
		$this->test->save();
		//更新试卷题数
		$this->success('共生成 '.($number-1) .'道题');
	}

	public function chooseitem()
    {
		/*
		 * 获取目前试卷试题
		*/
		$items = $this->model->where(['test_id'=>$this->test['id']])->select();
		$items = $items ? collection($items)->toArray() : [];
		$items_ids = array_column($items, 'item_id');
		/*
		 * 获取题库同科目试题
		*/
		$list = Itembank::where(['article_id'=>$this->test['article_id']])->select();
		$list_judge = [];
		$list_onechoice = [];
		$list_manychoice = [];
		//处理结果
		foreach($list as $key=>$val){
			$offset = array_search($val['id'],$items_ids);
			if($offset || $offset === 0){
				$val['checked'] = 1;
				$val['score'] = $items[$offset]['score'];
				$val['weigh'] = $items[$offset]['weigh'];
			}else{
				$val['checked'] = 0;
				$val['score'] = '';
				$val['weigh'] = 0;
			}
			if($val['type'] == 'judge'){
				$list_judge[] = $val;
			}else if($val['type'] == 'onechoice'){
				$list_onechoice[] = $val;
			}else if($val['type'] == 'manychoice'){
				$list_manychoice[] = $val;
			}

		}
		$this->view->assign('list',$list);
		$this->view->assign('list_judge',$list_judge);
		$this->view->assign('list_onechoice',$list_onechoice);
		$this->view->assign('list_manychoice',$list_manychoice);
        return $this->view->fetch();
    }

	/*
	* 选择试题完成操作
	*/
	public function postChooseItem()
    {
		/*
		 * 获取目前试卷试题
		*/
		
		if ($this->request->isAjax())
        {
			//严重试卷是否已有用户答卷
			$this->checkTest();
			
			$param = $this->request->post('');
			
			$totalInsertNum = 0;
			$totalUpdateNum = 0;
			if(isset($param['row'])){//判断参数
				$row = $param['row'];
				foreach($row as $key=>$val){
					//剔除没选中的
					if(isset($val['select']) && $val['select'] == 'checked'){
						if(empty($val['score'])){
							$this->error("ID=".$val['id']."这道题题未设置分数！");
							die;
						}
						//查询是否有这道题
						$itemInfo = TestitemModel::where(['test_id'=>$this->test['id'],'item_id'=>$val['id']])->find();
						if($itemInfo){
							//有这道题，判断分数排序是否变化，变化则更新
							if($itemInfo['score'] != $val['score'] || $itemInfo['weigh'] != $val['weigh']){
								$itemInfo->score = $val['score'];
								$itemInfo->weigh = $val['weigh'];
								$itemInfo->save();
								$totalUpdateNum++;
							}
						}else{
							//没有新增
							$itemInfo = new TestitemModel;
							$itemInfo->test_id = $this->test['id'];
							$itemInfo->item_id = $val['id'];
							$itemInfo->score = $val['score'];
							$itemInfo->weigh = $val['weigh'];
							$itemInfo->save();
							$totalInsertNum++;
						}
					}
				}
				//统计试卷总分
				$total_score = $this->model->where('test_id', $this->test['id'])->sum('score');
				$this->test->total_score = $total_score;
				$this->test->save();
				$this->success("新增".$totalInsertNum."道题，更新".$totalUpdateNum."道题");
			}
			$this->error("参数错误！");
		}
    }

	function checkTest(){
		//获取是否有人答题
		$total_user = Testuser::where(['test_id'=>$this->test['id']])->count();
		if($total_user > 0){
			$this->error("不允许操作，已有用户答题该试卷！");
		}
	}

}
